package cn.com.inossem.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.foxykeep.datadroid.requestmanager.Request;

import java.util.ArrayList;

import butterknife.ButterKnife;
import cn.com.inossem.activity.R;
import cn.com.inossem.entity.StatusEnum;
import cn.com.inossem.requestmanager.WooRequestManager;
import cn.com.inossem.systembartint.SystemBarTintManager;
import cn.com.inossem.utils.ActivityStackControlUtil;
import cn.com.inossem.utils.Utils;

/**
 * 全局基类
 * <p>
 * 1,bind to Datadroid to use 2,bind the lifecycle of activity to Datadroid
 * callback 3, process the loading and error
 * </p>
 *
 * @author wuyt3 2014-7-9
 * @see
 * @since 1.0
 */

public abstract class RequestActivity extends FragmentActivity implements
        RequestBaseUi, OnClickListener {
    protected static final String SAVED_STATE_REQUEST_LIST = "saved_state_request_list";

    protected WooRequestManager mRequestManager = null;

    protected ArrayList<Request> mRequestList = null;

    protected boolean mContextDestroyed = false;

    private FragmentManager mFragmentManager;

    private FragmentTransaction mFragmentTransaction;

    private ProgressDialog progressDialog = null;

    private Context context = RequestActivity.this;

    protected StatusEnum statusEnum;
    private ProgressDialog pd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("LEIJIA",this.getClass().getName().toString());
//        System.out.println(this.getClass().getName().toString());
        setContentView(getContentViewId());
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }

        // 创建状态栏的管理实例
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        // 激活状态栏设置
        tintManager.setStatusBarTintEnabled(true);
        // 激活导航栏设置
        // tintManager.setNavigationBarTintEnabled(true);
        // 设置一个颜色给系统栏
        tintManager.setTintColor(getResources().getColor(R.color.app_main));
        // 设置一个样式背景给导航栏
        // tintManager.setNavigationBarTintResource(R.drawable.my_tint);
        // 设置一个状态栏资源
        // tintManager.setStatusBarTintDrawable(MyDrawable);

        initAllMembers(savedInstanceState);
        ActivityStackControlUtil.add(this);
        if (Utils.isNetworkAvailable(this)) {
            Request request = getInitialRequest();
            if (request == null) {
                return;
            }
            launchRequest(request);
            if (needShowLoadingIndicator()) {
                onLoadingIndicatorShow(statusEnum);
            }
        } else {
            Toast.makeText(this, "未检查到可用的网络！", Toast.LENGTH_LONG).show();
            handleException(EXCEPTION_TYPE_NETWORK);
        }
    }

    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }


    @Override
    public void onDestroy() {
        mContextDestroyed = true;
        ActivityStackControlUtil.remove(this);
        super.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelableArrayList(SAVED_STATE_REQUEST_LIST, mRequestList);
    }

    @Override
    public void initAllMembers(Bundle savedInstanceState) {
        mContextDestroyed = false;
        mRequestManager = WooRequestManager.from(this);
        mFragmentManager = getSupportFragmentManager();
        if (savedInstanceState != null) {
            mRequestList = savedInstanceState
                    .getParcelableArrayList(SAVED_STATE_REQUEST_LIST);
        }
        if (mRequestList == null) {
            mRequestList = new ArrayList<Request>();
        }
    }

    @Override
    public void initLoader() {
    }

    public Request getInitialRequest() {
        return null;
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 发起请求
     */
    @Override
    public final void launchRequest(Request request) {
        if (request != null) {
            if (Utils.isNetworkAvailable(this)) {
                mRequestManager.execute(request, this);
                mRequestList.add(request);
                onLoadingIndicatorShow(statusEnum);
            } else {
                handleException(EXCEPTION_TYPE_NETWORK);
            }
        }
    }

    @Override
    public final void onRequestConnectionError(Request arg0, int arg1) {
        if (mRequestList.contains(arg0)) {
            mRequestList.remove(arg0);
        }
        // Toast.makeText(this, R.string.global_server_no_response,
        // Toast.LENGTH_SHORT).show();
        if (arg1 == -1) {
            handleException(EXCEPTION_TYPE_NETWORK);
        } else {
            handleException(EXCEPTION_TYPE_SERVER_NO_RESPONSE);
        }
    }

    @Override
    public final void onRequestCustomError(Request arg0, Bundle arg1) {
        if (mRequestList.contains(arg0)) {
            mRequestList.remove(arg0);
        }
        handleException(EXCEPTION_TYPE_CUSTOM_BASE);
    }

    @Override
    public final void onRequestDataError(Request arg0) {
        if (mRequestList.contains(arg0)) {
            mRequestList.remove(arg0);
        }
        // Toast.makeText(this, R.string.get_request_data_faild,
        // Toast.LENGTH_LONG)
        // .show();
        handleException(EXCEPTION_TYPE_DATA);
    }

    @Override
    public final void onRequestFinished(Request arg0, Bundle arg1) {
        if (mContextDestroyed) {
            return;
        }

        if (mRequestList.contains(arg0)) {
            onLoadingIndicatorHide();
            initLoader();
            onRequestSucess(arg0, arg1);
            mRequestList.remove(arg0);
        }
    }

    @Override
    public final void handleException(int exceptionType) {
        if (mContextDestroyed) {
            return;
        }
        onLoadingIndicatorHide();
        onRequestError(exceptionType);
    }

    @Override
    public void onRequestSucess(Request request, Bundle bundle) {
    }

    @Override
    public void onRequestError(int exceptionType) {
        View errorIndicatorLayout = getErrorIndicatorLayout();
        TextView errorMsgTextView = getErrorMsgTextView();
        if (errorIndicatorLayout == null || errorMsgTextView == null) {
            return;
        }
    }

    @Override
    public View getErrorIndicatorLayout() {
        return null;
    }

    @Override
    public TextView getErrorMsgTextView() {
        return null;
    }

    @Override
    public View getLoadingIndicatorView() {
        return null;
    }

    @Override
    public boolean needShowLoadingIndicator() {
        return true;
    }

    @Override
    public void onLoadingIndicatorShow(StatusEnum statusEnum) {
        this.statusEnum = (StatusEnum) statusEnum;
        View view = getLoadingIndicatorView();
        if (view != null) {
            view.setVisibility(View.VISIBLE);
        }
        if (null == progressDialog) {
            progressDialog = new ProgressDialog(context);
            progressDialog.setIndeterminate(true);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    progressDialog.dismiss();
                }
            });

        }

        if (null != statusEnum) {
            switch (statusEnum) {

                case GROUDDETAIL:
                    // progressDialog.setMessage(getString(R.string.grouddetail));
                    // progressDialog.show();
                    break;

                default:
                    break;
            }
        }

    }

    @Override
    public final void onLoadingIndicatorHide() {
        View view = getLoadingIndicatorView();
        if (view != null) {
            view.setVisibility(View.GONE);
        }
        if (progressDialog != null)
            progressDialog.dismiss();

    }

    public void showLoadPd() {
        if (null == pd) {
            pd = new ProgressDialog(this);
            pd.setMessage("加载中...");
            pd.setCanceledOnTouchOutside(false);
        }
        pd.show();
    }

    public void dismissLoadPd() {
        if (null != pd) {
            pd.dismiss();
        }
    }
}
